package com.adobe.apprise.commands
{
	import com.adobe.air.alert.NativeAlert;
	import com.adobe.apprise.database.DatabaseEvent;
	import com.adobe.apprise.database.DatabaseResponder;
	import com.adobe.apprise.events.ExportFeedsEvent;
	import com.adobe.apprise.model.ModelLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import flash.desktop.NativeApplication;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class ExportFeedsCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var saveFile:File = ExportFeedsEvent(ce).feedFile;

			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					var feeds:Array = e.data;
					if (feeds == null || feeds.length == 0) return;

					XML.prettyIndent = 4;

					var opml:XML = <opml version="1.0"/>
					opml.appendChild(<head><title>Export From Apprise</title></head>);
					var body:XML = <body/>
					opml.appendChild(body);

					for each (var feed:Object in feeds)
					{
						var outline:XML = <outline/>
						if (feed.name != null)
						{
							outline.@title = feed.name;
						}
						if (feed.feed_url != null)
						{
							outline.@xmlUrl = feed.feed_url;
						}
						if (feed.site_url != null)
						{
							outline.@htmlUrl = feed.site_url;
						}
						body.appendChild(outline);
					}

					var fs:FileStream = new FileStream();
					fs.open(saveFile, FileMode.WRITE);
					fs.writeUTFBytes("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + opml.toXMLString());
					fs.close();
					NativeAlert.show("Your feeds have been saved.",
									 "Export Complete",
									 NativeAlert.OK,
									 true,
									 NativeApplication.nativeApplication.openedWindows[0]);
				});

			ModelLocator.getInstance().db.getFeeds(responder);
		}
	}
}
